package com.as3.timbot.net
{
	import com.as3.timbot.net.AbstractLoader;
	import com.as3.timbot.utils.media.ID3Reader;
	import com.as3.timbot.net.LoadEvent;
	import com.as3.timbot.events.BytesEvent;
	import com.as3.timbot.net.strategies.RangeFinder;
	
	import flash.utils.ByteArray;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLStream;
	import flash.net.URLRequest;
	
	
	public class ID3Loader extends AbstractLoader
	{
		private var __stream:URLStream;
		private var __url:String;
		private var __request:URLRequest;
		
		public function ID3Loader(_value:String, _zipped:Boolean)
		{
			super(_value, _zipped);
			__url = _value;
		}
		/**
		*	Calls the superclass to begin loading the asset
		*
		* 	@langversion ActionScript 3.0
		*	@playerversion Flash 9.0
		*	@tiptext
		*/
		public function load():void
		{
		 	var strategy:RangeFinder = new RangeFinder();
			strategy.addEventListener(RangeFinder.COMPLETE,getID3Length);
			strategy.getByteRange(__url,10);
		
			//the AbstractLoader always loads from Zero to EndByte, makes a byteArray,
			//and passes it to the subclass to cast
		}
		
		/**
		*	Strategy to retrieve the ID3 information from a byte array
		* 
		*	@param _bytes The byte array to be cast to a type
		 * 
		* 	@langversion ActionScript 3.0
		*	@playerversion Flash 9.0
		*	@tiptext
		*/
		override protected function castType(_bytes:ByteArray):void
		{
			//extract the ID3 tag info from the bytes in here...
			var myID3Reader:ID3Reader = new ID3Reader();
			myID3Reader.addEventListener(LoadEvent.LOADCOMPLETE,castFinish);
			myID3Reader.load(_bytes);
		}
		
		public function castFinish(ev:LoadEvent):void
		{
			super.castComplete(ev.getContent());
		}
		
		/**
		*	Strategy to receive the length of an ID3 tag
		* 
		*	@param _byteStream The byte array containin ID3 tag length value
		* 
		* 	@langversion ActionScript 3.0
		*	@playerversion Flash 9.0
		*	@tiptext
		*/
		private function getID3Length(ev:BytesEvent):void
		{
			
			var _bytes:ByteArray = ev.getBytes();
			
			if (_bytes.readUTFBytes(3).toUpperCase()=="ID3") 
			{
				_bytes.readByte();
				_bytes.readByte(); // storing tag version
				_bytes.readByte(); // storing flags byte
				var length:uint = _bytes.readInt();
				//////////////////////new/////////////////////////////
				super.setCloseByte(length);
				super.loadAsset();
				/////////////////////////////////////////////////////
				} else { 
					trace("error"); 
				}
		}
	}
}